<template>
  <PageWrapper>
    <div
      class="page-empty"
      v-show="tenantTree.originTreeData.length === 0 && !tenantTree.initDataLoading && !tenantTree.searchConfirmVAlue"
    >
      <Empty positionType="relative" description="暂无租户数据，去租户管理新增吧！"></Empty>
      <a-button
        type="primary"
        style="margin-top: 16px"
        v-auth="permissionCodeMap.tenantAdd"
        @click="goPage({ name: 'tenantManage', params: { type: 'add' } })"
      >
        新增租户
      </a-button>
    </div>
    <div
      class="page-tenant"
      v-show="
        !(tenantTree.originTreeData.length === 0 && !tenantTree.initDataLoading && !tenantTree.searchConfirmVAlue)
      "
    >
      <div class="tenant-tree">
        <div class="tree-title">租户信息</div>
        <div class="tree-main" v-loading="tenantTree.initDataLoading">
          <div class="main-search">
            <a-input-search
              allowClear
              v-model:value.trim="tenantTree.searchValue"
              placeholder="请输入关键字"
              @search="inputChange"
            >
            </a-input-search>
          </div>
          <div class="main-tree">
            <div :class="['tree-all', tenantTree.selectedKeys ? '' : 'tree-active']" @click="selectChange('')">
              <IconFont iconType="icon-qiyeguanli_icon" :customStyle="{ fontSize: '14px' }" />
              <div class="item-name">全部租户（{{ pageObj.total }}）</div>
            </div>
            <div
              :class="['tree-item', tenantTree.selectedKeys === item.tenantId ? 'tree-active' : '']"
              v-for="item in tenantTree.originTreeData"
              @click="selectChange(item.tenantId)"
              :key="item.tenantId"
            >
              <div class="item-name">{{ item.orgName }}</div>
            </div>
          </div>
          <div class="main-page">
            <div class="page-num">
              <left-outlined v-if="pageObj.current < 2" class="num-arrow num-disabled" />
              <left-outlined @click="currentChange('reduce')" v-else class="num-arrow" />
              <a-input-number
                :controls="false"
                @blur="currentChange('change')"
                @keypress.enter="currentChange('change')"
                v-model:value="pageObj.current"
                size="small"
                :precision="0"
                :min="1"
                :max="pageNumber"
              />
              <div class="num-separator">／</div>
              <div class="num-size">{{ pageNumber }}</div>
              <right-outlined v-if="pageObj.current < pageNumber" class="num-arrow" @click="currentChange('add')" />
              <right-outlined v-else class="num-arrow num-disabled" />
            </div>
            <a-select v-model:value="pageObj.pageSize" style="width: 90px" size="small" @change="pageSizeChange">
              <a-select-option :key="item.value" :value="item.value" v-for="item in selectPageArr">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </div>
        </div>
      </div>
      <div class="tenant-table">
        <div class="table-company">
          <div class="company-name">{{ getSelectCompany.orgName ? getSelectCompany.orgName : '全部租户' }}</div>
          <user-outlined :style="{ fontSize: '12px', color: '#4AA353', margin: '0 4px 0 14px' }" />
          <div class="company-total">{{ tenantTree.total }}人</div>
        </div>
        <div class="table-main">
          <BasicTable
            @register="registerTable"
            @fetch-success="onFetchSuccess"
            :rowSelection="
              checkboxShow
                ? {
                    type: 'checkbox',
                    columnWidth: 44,
                    selectedRowKeys: checkedDelKeys,
                    onChange: onSelectChange,
                    getCheckboxProps: onGetCheckboxProps
                  }
                : null
            "
            :searchInfo="{
              topTenantId: tenantTree.selectedKeys,
              topOrgName: tenantTree.searchConfirmVAlue
            }"
          >
            <template #tableTitle>
              <a-space :size="12">
                <a-button
                  type="primary"
                  v-if="tenantTree.selectedKeys"
                  v-auth="permissionCodeMap.tenantUserAdd"
                  @click="openUserOrganization"
                  >新增用户</a-button
                >
                <a-button
                  danger
                  v-auth="permissionCodeMap.tenantUserDel"
                  :disabled="!checkedDelKeys.length"
                  @click="operateDel('batchDel')"
                  >批量删除</a-button
                >
              </a-space>
            </template>

            <template #bodyCell="{ column, record, text }">
              <template v-if="column.dataIndex === 'authRemainingDays'">
                <div class="last-time">
                  <span class="time-num" v-if="record.authRemainingDays || record.authRemainingDays == 0">
                    {{ record.authRemainingDays }}
                  </span>
                  <span>{{ record.authRemainingDays || record.authRemainingDays === 0 ? '天' : '永久' }}</span>
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'phoneNumber'">
                <div class="custome-phone">{{ record.phoneNumber }}</div>
              </template>
              <template v-else-if="column.dataIndex === 'email'">
                <div class="custome-email">{{ record.email }}</div>
              </template>
              <template v-else-if="column.dataIndex === 'userStatus'">
                <span class="global-active-status" v-if="record.userStatus == 0"> 正常</span>
                <span class="global-stop-status" v-else-if="record.userStatus == 1"> 禁用 </span>
                <span v-else>--</span>
              </template>
              <template v-else-if="column.dataIndex === 'operate'">
                <a-button
                  type="link"
                  class="g-operate-btn"
                  v-if="record.userType != 1"
                  v-auth="permissionCodeMap.tenantUserStatus"
                  @click="operateStatus(record)"
                >
                  {{ record.userStatus == 0 ? '禁用' : '启用' }}
                </a-button>
                <a-button
                  type="link"
                  class="g-operate-btn"
                  v-if="record.userType != 1"
                  v-auth="permissionCodeMap.tenantUserAuth"
                  @click="openUserAuthOrganization(record)"
                  >{{ record.tenantUserAuthFlag === 1 ? '授权' : '' }}</a-button
                >
                <a-button
                  type="link"
                  danger
                  class="g-operate-btn"
                  v-if="record.userType != 1"
                  v-auth="permissionCodeMap.tenantUserDel"
                  @click="operateDel('del', record)"
                  >删除</a-button
                >
              </template>
            </template>
          </BasicTable>
        </div>
      </div>
    </div>
    <TenantUserAdd @register="tenantUserAddRegister" @operateSuccess="resetListData" />
    <TenantUserAuth @register="tenantAuthRegister" @operateSuccess="resetListData" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, onMounted, nextTick, onActivated, createVNode } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getTenantBasicColumns, getSearchFormConfig } from './dataSource'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'
import TenantUserAdd from './components/TenantUserAdd.vue'
import TenantUserAuth from './components/TenantUserAuth.vue'
import Empty from '@/components/Empty/index.vue'
import { userStore } from '@/store/modules/user'
import { toEleTreeData } from '@/utils'
import { treeFilter } from '@/utils/treeHelper'
import { cloneDeep } from 'lodash-es'
import { useRoute } from 'vue-router'
import { useGoPage } from '@/hooks/useGoPage'

import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { TenantRecord } from '@/types/tenant'
import {
  SearchOutlined,
  UserOutlined,
  ExclamationCircleFilled,
  LeftOutlined,
  RightOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import IconFont from '@/components/IconFont/index.vue'
import api from '@/api'
const { enterpriseUserList, enterpriseList, updateStatusById, enterpriseUserDelete } = api
const userModule = userStore()
const route = useRoute()

const goPage = useGoPage()

const operateActionTypeMap = operateActionType
const currentTenantId = ref('')
const checkedDelKeys = ref<Array<string | number>>([])

const tenantTree = reactive<any>({
  searchValue: '',
  searchConfirmVAlue: '',
  initDataLoading: false,
  originTreeData: [],
  selectedKeys: '',
  total: 0
})

const pageObj = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const selectPageArr = [
  { label: '10条/页', value: 10 },
  { label: '20条/页', value: 20 },
  { label: '50条/页', value: 50 },
  { label: '100条/页', value: 100 }
]
const [tenantUserAddRegister, { openModal: tenantUserOpenModal }] = useModal()
const [tenantAuthRegister, { openDrawer: userAuthOpenDrawer }] = useDrawer()

const [registerTable, { reload, setPagination }] = useTable({
  api: enterpriseUserList,
  columns: getTenantBasicColumns(),
  useSearchForm: true,
  formConfig: getSearchFormConfig(),
  showIndexColumn: true,
  rowKey: 'userId',
  immediate: false, //初始化不请求数据
  scroll: { y: 'calc(100vh - 470px)', x: constantMap.tableXWidth }
})

const getSelectCompany: any = computed(() => {
  let selectItem = {}
  if (tenantTree.selectedKeys) {
    selectItem = tenantTree.originTreeData.find((item: any) => item.tenantId === tenantTree.selectedKeys) || {}
  }
  return selectItem
})

const pageNumber = computed(() => {
  return Math.ceil(pageObj.total / pageObj.pageSize)
})

const checkboxShow = computed(() => userModule.permissionActionList.includes(permissionCodeMap.tenantUserDel))

// 获取租户所有的机构列表
const getEnterpriseAllList = async () => {
  try {
    tenantTree.initDataLoading = true
    let res = await enterpriseList({
      orgName: tenantTree.searchValue,
      page: {
        pageNo: pageObj.current,
        pageSize: pageObj.pageSize
      }
    })

    pageObj.total = res.result.total || 0
    tenantTree.originTreeData = res.result?.records || []
    tenantTree.initDataLoading = false

    nextTick(() => {
      reload()
    })
  } catch (error) {
    tenantTree.initDataLoading = false
  }
}

const currentChange = (type: string) => {
  if (type === 'add') {
    pageObj.current = pageObj.current + 1
  } else if (type === 'reduce') {
    pageObj.current = pageObj.current - 1
  } else if (type === 'change') {
    pageObj.current = pageObj.current || 1
  }
  tenantTree.selectedKeys = ''
  getEnterpriseAllList()
}
const pageSizeChange = () => {
  pageObj.current = 1
  tenantTree.selectedKeys = ''
  getEnterpriseAllList()
}

const inputChange = (value: string) => {
  tenantTree.searchConfirmVAlue = value || ''
  pageSizeChange()
}

// 禁止删除用户
const onGetCheckboxProps = (record: any) => {
  return {
    disabled: record.userStatus == 0 || record.userType == 1
  }
}
const onSelectChange = (selectedRowKeys: (string | number)[]) => {
  checkedDelKeys.value = selectedRowKeys
}

const openUserAuthOrganization = (record: any) => {
  userAuthOpenDrawer(true, {
    record
  })
}
const openUserOrganization = () => {
  tenantUserOpenModal(true, {
    tenantId: tenantTree.selectedKeys,
    selectCompany: getSelectCompany.value
  })
}

onActivated(() => {
  getEnterpriseAllList()
})

const onFetchSuccess = ({ items, total }: any) => {
  tenantTree.total = total || 0
}
const resetListData = () => {
  setPagination({
    current: 1,
    total: 0
  })
  nextTick(() => {
    reload()
  })
}
// 节点选择变化
const selectChange = (selectedKeys: string) => {
  tenantTree.selectedKeys = selectedKeys
  resetListData()
}

const operateStatus = (record: any) => {
  let contentInfo = record.userStatus === 1 ? '启用' : '禁用'
  Modal.confirm({
    title: '提示',
    centered: true,
    icon: createVNode(ExclamationCircleFilled),
    content: `是否确认${contentInfo} ${record.userName} 的账户使用权限`,
    autoFocusButton: null,
    class: 'modal-confirm-box',
    async onOk() {
      await updateStatusById({
        userId: record.userId,
        userStatus: record.userStatus === 1 ? 0 : 1
      })
      message.success(`${contentInfo}账户成功`)
      resetListData()
    },
    onCancel() {}
  })
}
const operateDel = (type: string, record?: any) => {
  if (type === 'del') {
    if (record.userStatus != 1) {
      return message.error('请先禁用用户后删除')
    }
  }
  Modal.confirm({
    title: type === 'del' ? '确定删除该用户？' : '确定批量删除所选用户？',
    centered: true,
    icon: createVNode(ExclamationCircleFilled),
    content: `删除后数据不可恢复`,
    autoFocusButton: null,
    class: 'modal-confirm-box',
    async onOk() {
      await enterpriseUserDelete({
        userIdList: type === 'del' ? [record.userId] : checkedDelKeys.value
      })
      message.success(`删除成功`)
      resetListData()
    },
    onCancel() {}
  })
}
</script>

<style lang="less" scoped>
.page-tenant {
  min-height: calc(100vh - 200px);
  display: flex;
  align-items: flex-start;
  .tenant-tree {
    flex-shrink: 0;
    width: 284px;
    min-width: 220px;
    border: 1px solid #e0e1e6;
    border-radius: 4px;
    .tree-title {
      height: 44px;
      line-height: 44px;
      padding-left: 16px;
      font-size: 16px;
      background: #fafafa;
      font-weight: 500;
      border-bottom: 1px solid #e0e1e6;
    }
    .tree-main {
      position: relative;
      // overflow-y: auto;
      :deep(.main-search) {
        margin: 16px;
        .anticon-search {
          color: #555d6f;
          font-size: 14px;
        }
      }
      .main-tree {
        height: calc(100vh - 344px);
        overflow-y: auto;
        padding: 0 16px;
        font-size: 12px;
        line-height: 22px;
        .tree-all {
          margin-bottom: 8px;
          display: flex;
          align-items: center;
          cursor: pointer;
          &.tree-active {
            color: @primary-color;
          }
          &:hover {
            color: @primary-color;
          }
          .item-name {
            padding-left: 4px;
          }
        }
        .tree-item {
          margin-bottom: 8px;
          cursor: pointer;
          .item-name {
            padding-left: 18px;
          }
          &.tree-active {
            color: @primary-color;
          }
          &:hover {
            color: @primary-color;
          }
        }
      }
      :deep(.main-page) {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px;
        .page-num {
          font-size: 12px;
          display: flex;
          align-items: center;
          color: #545d70;
          .num-arrow {
            cursor: pointer;
            &:hover {
              color: @primary-color;
            }
            &.num-disabled {
              color: #c0c0c0;
              cursor: not-allowed;
              &:hover {
                color: #c0c0c0;
              }
            }
          }
          .ant-input-number {
            width: 48px;
            margin-left: 8px;
            input {
              text-align: center;
              color: #565c6e;
            }
          }
          .num-separator {
            color: #545d70;
            font-size: 14px;
            margin: 0 12px 0 16px;
          }
          .num-size {
            color: #565c6e;
            margin-right: 8px;
          }
        }
        .ant-select,
        .ant-select-item {
          font-size: 12px;
        }
      }
    }
  }
  .tenant-table {
    flex: 1;
    margin-left: 16px;
    overflow-x: hidden;
    .table-company {
      height: 44px;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      .company-name {
        font-weight: 500;
        color: #172237;
        line-height: 22px;
        font-size: 16px;
      }
      .company-total {
        font-size: 12px;
      }
    }
    .time-num {
      color: @primary-color;
    }
    .custome-phone {
      min-width: 140px;
    }
    .custome-email {
      min-width: 160px;
    }
  }
}
.page-empty {
  min-height: calc(100vh - 170px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
